from flask import jsonify,Blueprint,request
import json
from db import db1
from jwt1 import myjwt
from utils.acl import acl
from utils.red1 import red

bp_user = Blueprint('user',__name__)


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data



@bp_user.route('/login',methods=['POST','GET'])
def login():
    data = get_data()
    sql = "select * from user where username='%s' and password='%s'" % (data['username'], data['password'])
    res = db1.find(sql)
    token = myjwt.jwt_encode({'data':{'uid':res['id']}})
    #vue页面
    #白名单
    # pagelist = acl.get_page_reslist(res['id'])
    # 接口路由
    #钩子函数拦截器
    # interfacelist = acl.get_interface_reslist(int(res['id']))
    # key = 'uid' + str(res['id'])
    # red.insert_set(key,interfacelist)
    if res:
        return jsonify(
            #有拦截器返回
            # {'code': 200, 'userid': res['id'],'token':token,"url":pagelist})
            #没有拦截器
            {'code': 200, 'userid': res['id'], 'token': token})
    else:
        return jsonify({'code': 20010, 'mes': '用户名或密码错误'})


#redis哈希类型存取
@bp_user.route('/test1')
def test1():
    key = 'abac'
    red.insert_hash(key,'ip','127.0.0.1')
    red.insert_hash(key,'level','003')
    red.insert_hash(key,'time','["2021-10-10","2021-12-10"]')
    values = red.get_all_hash(key)
    # print(json.loads(values))
    for (k,v) in values.items():
        if str(k,encoding='utf8') == 'time':
            print(eval(v))
            print(eval(v)[0])
            print(eval(v)[1])
    return 'ok'

@bp_user.route('/sho_work')
def show_work():
    sql = '''select * from workflow'''
    d = db1.fid_all(sql)
    return jsonify({"code":200,'list':d})

@bp_user.route('/show_table',methods=['POST','GET'])
def show_table():
    if request.method == 'GET':
        #先从redis取
        value = red.str_get('dataresouce')
        if value:
            list = eval(value)
        else:
            sql = '''select * from data_source'''
            d = db1.fid_all(sql)
            list = []
            if d:
                for i in d:
                    dict={'id':i['id'],'name':i['name']}
                    sql1 = '''select id,name,type from %s'''%(i['table'])
                    subres = db1.fid_all(sql1)
                    dict['mes'] = subres
                    list.append(dict)
            red.str_set('dataresouce', json.dumps(list))
        return jsonify({"code":200,'list':list})
        


# 数据源
@bp_user.route('/origin',methods=['POST','GET'])
def origin():
    if request.method=='POST':
        gain = request.form.to_dict()
        sql = """update workflow set params='%s' where id=%d""" % (gain['list'], int(gain['id']))
        db1.update(sql)
        return jsonify({'code': 200,'mes':'添加成功'})
    else:
        id = request.args.get('id')
        sql = '''select * from workflow where id=%d '''%int(id)
        d = db1.find(sql)
        return jsonify({"code":200,'list':d})

#获取审批人
@bp_user.route('/show_role',methods=['POST','GET'])
def show_role():
    if request.method=='GET':
        sql = '''select * from post'''
        d = db1.fid_all(sql)
        return jsonify({"code": 200, 'list': d})
    else:
        data = request.form.to_dict()
        ree = eval(data['result'])
        result = sorted(ree)
        sql = '''insert into approval(params,user_id,post_id,sort) values('%s',%d,'%s',%d)'''%(data['form'],int(data['userid']),str(result),(result[-1]))
        db1.update(sql)
        return jsonify({"code":200})

@bp_user.route('/show_app',methods = ['POST','GET'])
def show_app():
    if request.method == 'GET':
        id = request.args.get('id')
        # 登录者的数据
        sql = '''select post.id,user.post_id,post.coding from user left join post on user.post_id=post.id where user.id=%d'''%(int(id))
        shuju = db1.find(sql)
        #审批人都有谁
        sql1 = '''select * from approval '''
        post_id1 = db1.fid_all(sql1)
        post_id = []
        for i in post_id1:
            post_id = i['post_id']
        result = sorted(eval(post_id))
        #判断登录者是不是某审批人
        if int(shuju['coding']) in result:
            # 判断登录者是不是最低级审批人
            if result[-1] == int(shuju['coding']):
                #如果是就返回该用户该有的审批列表
                sql2 = '''select * from approval where sort = %d'''%int(shuju['coding'])
                sql2_list = db1.fid_all(sql2)
                for i in sql2_list:
                    params = eval(i['params'])
                    i['params'] = params
                return jsonify({"code":200,"list":sql2_list})
            else:
                该写上级审批人
                ！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
                print('123132123123')
        else:
            print('no')
        return jsonify({"code":200})
    else:
        data = get_data()
        #用户表查找用户
        sql = '''select post_id from user where id=%d'''%int(data['user_id'])
        user = db1.find(sql)

        #查询请假流程表中是否有这条请假记录
        sql4 = '''select approval_id from liuc where approval_id=%d'''%int(data['approval_id'])
        liuc = db1.find(sql4)
        if liuc:
            #添加到请假详情表
            sql3 = '''insert into liuc(user_id,post_id,text,type,approval_id) values(%d,%d,'%s',1,%d) '''\
                   %(int(data['user_id']),int(user['post_id']),data['text'],int(data['approval_id']))
            # db1.update(sql3)
            #修改总请假表中状态 审批中、推进审批人
            sql2 = '''update approval set sort=sort-1,type=2 where id= %d'''%int(data['approval_id'])
            # bbb = db1.update(sql2)
            return jsonify({"code":200})
        else:
            return jsonify({"code":10010,'mes':'已经审批过了'})



